import { createApplication, start } from './application';


async function loadJsListFile(url: string) {
    return new Promise(function (resolve, reject) {
        let err: any;

        function windowErrorListener(evt:any) {
            if (evt.filename === url) {
                err = evt.error;
            }
        }

        window.addEventListener('error', windowErrorListener);
        const script = document.createElement('script');
        script.charset = 'utf-8';
        script.async = true;
        script.crossOrigin = 'anonymous';
        script.addEventListener('error', function () {
            window.removeEventListener('error', windowErrorListener);
            reject(Error('Error loading ' + url));
        });
        script.addEventListener('load', function () {
            window.removeEventListener('error', windowErrorListener);
            document.head.removeChild(script);
            // Note that if an error occurs that isn't caught by this if statement,
            // that getRegister will return null and a "did not instantiate" error will be thrown.
            if (err) {
                reject(err);
            } else {
                // @ts-ignore
                resolve();
            }
        });
        script.src = url;
        document.head.appendChild(script);
    });
}

function fetchWasm(url: string) {
    return fetch(url).then(function (response) {
        return response.arrayBuffer();
    });
}

function findCanvas() {

}

export const Engine = {
    load() {
        createApplication(
            {
                loadJsListFile, fetchWasm,
            },
        ).then(() => {
            start({
                findCanvas,
            });
        });
    },
};
